<template>
    <n-modal
        ref="modalRef"
        preset="dialog"
        title="编辑"
        :close-on-esc="!loading"
        :mask-closable="!loading"
        v-model:show="showModel"
    >
        <Form
            ref="formRef"
            :items="items"
            :loading="loading"
            v-model:value="formState"
            style="margin-top: 20px"
            :form-props="formProps"
        >
            <template #tool> </template>
        </Form>

        <template #action>
            <n-space>
                <n-button @click="onCancel" :disabled="loading">取消</n-button>
                <n-button type="primary" @click="onConfirm" :loading="loading"
                    >确定</n-button
                >
            </n-space>
        </template>
    </n-modal>
</template>

<script setup lang="ts">
import { computed, PropType, ref } from 'vue'
import { FormItemsConfig, FormStateType } from '../types'
import Form from './Form.vue'
import { FormInst, FormProps } from 'naive-ui'

const emits = defineEmits<{
    submit: []
    'update:value': [newValue: FormStateType]
    'update:show': [newValue: boolean]
}>()

const props = defineProps({
    items: {
        type: Object as PropType<FormItemsConfig<any>>,
        required: true
    },
    value: {
        type: Object,
        default: () => ({})
    },
    loading: {
        type: Boolean,
        default: () => false
    },
    show: {
        type: Boolean,
        default: () => false
    },
    formProps: {
        type: Object as PropType<FormProps>,
        default: () => ({})
    }
})

const formState = computed({
    get: () => props.value,
    set: (val) => emits('update:value', val)
})

const formRef = ref<FormInst>()
function onConfirm() {
    formRef.value
        ?.validate()
        .then(() => {
            emits('submit')
        })
        .catch((_) => {
            // 占位
        })
}

const showModel = computed({
    get: () => props.show,
    set: (val) => emits('update:show', val)
})
function onCancel() {
    showModel.value = false
}
</script>
